package com.itx.gatewayx.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.WebFilter;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.Collections;

/**
 * Web配置类
 *
 * @author itx
 */
@Slf4j
@Configuration
public class WebConfig {
    
    /**
     * 请求日志过滤器，用于调试
     */
    @Bean
    public WebFilter requestLoggingFilter() {
        return (exchange, chain) -> {
            System.out.println("请求路径: " + exchange.getRequest().getPath());
            System.out.println("请求方法: " + exchange.getRequest().getMethod());
            System.out.println("请求头: " + exchange.getRequest().getHeaders());
            return chain.filter(exchange)
                .doOnSuccess(v -> System.out.println("响应状态: " + exchange.getResponse().getStatusCode()));
        };
    }
    
    /**
     * CORS跨域配置
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有来源
        config.setAllowedOriginPatterns(Collections.singletonList("*"));
        // 允许所有HTTP方法
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
        // 允许所有头信息
        config.setAllowedHeaders(Arrays.asList("*"));
        // 允许发送Cookie
        config.setAllowCredentials(true);
        // 预检请求的有效期，单位：秒
        config.setMaxAge(3600L);
        // 暴露头信息
        config.setExposedHeaders(Arrays.asList("Authorization", "Content-Type", "Access-Control-Allow-Origin"));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        // 创建CorsWebFilter并设置为最高优先级
        CorsWebFilter corsWebFilter = new CorsWebFilter(source);
        return corsWebFilter;
    }
} 